package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;
@Autowired
private ESManagerMapper esManagerMapper;
    @Override
    public void createIndexAndMapping() {
        //为 SkuInfo 类创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //放置 SkuInfo 类的映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        List<Sku> all = skuFeign.findSkuListBySpuId("all");
        if (all == null || all.size() < 0) {
            throw new RuntimeException("查询数据库数据失败");
        }
        String s = JSON.toJSONString(all);
        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);

        //将数据导入到 Elasticsearch 中
        for (SkuInfo skuInfo : skuInfos) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void importDataToESBySpuId(String spuId) {
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        if (skuListBySpuId == null || skuListBySpuId.size() < 0) {
            throw new RuntimeException("查询数据库数据失败");
        }
        String s = JSON.toJSONString(skuListBySpuId);
        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void delDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (skuList == null || skuList.size() < 0) {
            throw new RuntimeException("查询数据库数据失败");
        }
        for (Sku sku : skuList) {

            esManagerMapper.deleteById(Long.valueOf(sku.getId()));
        }

    }
}
